using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.SessionState;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using GURUCORE.Framework.Core;
using GURUCORE.Framework.Business;
using GURUCORE.Portal.Core;
using GURUCORE.Portal.Service.Business.DTO;
using GURUCORE.Lib.Core.Text;

namespace GURUCORE.Portal.Core.Controller
{
	public class RemapURL
	{
		public RemapURL()
		{
		}

		/// <summary>
		/// In RegexPattern, store in DB, we will replace this pattern with actual PageExtension
		/// </summary>
		const string PAGENAME = "##PAGENAME##";

		public const string EXTENSION = "EXTENSION";
		public const string EXTENSIONLESS = "EXTENSIONLESS";
		/// <summary>
		/// Remap with all URLMapper configuraion, return with first match
		/// </summary>
		/// <returns></returns>
		public  string Remap(string p_sRemapType, string p_sSourceURL, string p_sPageName)
		{
			string sResultURL = string.Empty;
			string sFindRegexPattern = string.Empty;
			string sReplaceRegexPattern = string.Empty;

		
			char[] arrTrimChar = {' ','&'};
            Hashtable htURLMapper = WebsiteApplication.GetInstance().GetSharedObject<Hashtable>(WebsiteApplication.URL_MAPPER_CACHE_KEY);

            foreach (string p_sRemapName in htURLMapper.Keys)
			{
                URLMapperDTO dtoMapper = (URLMapperDTO)htURLMapper[p_sRemapName];

				if(dtoMapper.Type != p_sRemapType)
				{
					continue;	// ignore not match type
				}

				// transfer the pattern into actual using pattern (replace some meta into actual value)
				sFindRegexPattern = TextHelper.FARA(	dtoMapper.FindRegexPattern, PAGENAME,  p_sPageName );
				sReplaceRegexPattern = dtoMapper.ReplaceRegexPattern;
				
				sResultURL =	TextHelper.FARA(p_sSourceURL	, sFindRegexPattern, sReplaceRegexPattern);
				if(sResultURL.TrimEnd(' ','&') != p_sSourceURL.TrimEnd(' ','&')  )	// sRet changed, match, remapped
				{
					break;
				}
			}

			return sResultURL;
		}


//		public string Remap(string p_sRemapName, string p_sSourceURL)
//		{
//			string sResultURL = string.Empty;
//            
//			sResultURL = TextProcessing.FARA(p_sSourceURL	, 
//				((Portal_URLMapperDTO)PortalApplication.URLMappers[p_sRemapName]).FindRegexPattern		, 
//				((Portal_URLMapperDTO)PortalApplication.URLMappers[p_sRemapName]).ReplaceRegexPattern
//				);
//
//			return sResultURL;
//		}

	}
}
